#include"socket.hpp"
#include<poll.h>
const int count=64;

const int no_event=0;
uint16_t default_port=8080;
const int defaultfd=-1;
class pollserver
{
  
  public:
  pollserver(uint16_t port=default_port)
  :_port(port)
  {
     for(int i=0;i<count;i++)
     {
        num[i].fd=defaultfd;
        num[i].events=no_event;
        num[i].revents=no_event;

     }
   


  }
  void accepter()
  {
    uint16_t clientport;
    string clientip;
    int sock=_listensock.Accept(&clientport,&clientip);
    if(sock<0)
    {cout<<"accept is error..."<<endl;}

    cout<<"clientport:"<<clientport<<" "<<"clientip:"<<clientip<<endl;

    int pos=1;
    for(;pos<count;pos++)
    {
      if(num[pos].fd==defaultfd)
        break;

    }
    //cout<<"pos:"<<pos<<endl;
    if(pos==count)
    {
         close(sock);
         cout<<"no position ...."<<endl;

    }
    else
    { cout<<"is ok"<<endl;
      num[pos].fd=sock;
      num[pos].events=POLLIN;
   
    }


  }
  void reader(int fd,int pos)
  {

   char buffer[1024];
   int n=read(fd,buffer,sizeof(buffer));
   if(n==0)
   {
      cout<<"client is quit ..."<<endl;
      close(fd);
      num[pos].fd=defaultfd;
      //num[pos].events=no_event;


   }
else if(n>0)
   {
     buffer[n-1]=0;
     string str=buffer;
     cout<<str<<endl;



   }
 else
   {
 
      cout<<"read error..."<<endl;
      close(fd);
      num[pos].fd=defaultfd;
     // num[pos].events=no_event;




   }


  }
  void handle()
  {

   for(int i=0;i<count;i++)
   {
    int fd=num[i].fd;
    if(fd==defaultfd)
     continue;
    if(num[i].events&&POLLIN)
    {
      if(fd==_listensock.fd())
      {

        accepter();


      }
      else
      {

       reader(fd,i);





      }












    }







   }













  }
  void init()
  {
   _listensock.Socket();
   _listensock.Bind(_port);
   _listensock.Listen();
  }
  void start()
  {
     num[0].fd=_listensock.fd();
     num[0].events=POLLIN;
     int timeout=3000;
     for( ;;)
     {
        int n=poll(num,count,timeout);
        
        switch(n)
        {

        case 0:
           cout<<"time out..."<<endl;

        break;
        case -1:
        cout<<"poll fail..."<<endl;

        break;
        default:
        handle();
        cout<<"poll is ok"<<endl;
         break;

        }

     }


     

  }
  

  private:
  struct pollfd num[count];
  sock _listensock;
  uint16_t _port;
};